//
//  SSDKPluginTimerUtil.m
//  SuperSDKPluginTools
//
//  Created by 涂俊 on 2017/11/1.
//  Copyright © 2017年 WYHT. All rights reserved.
//

#import "SSDKPluginTimerUtil.h"

@implementation SSDKPluginTimerUtil

+ (dispatch_source_t) createTimerWithInterval:(double)interval
                                   mainThread:(BOOL)mainThread
                                     startNow:(BOOL)startNow
                                      handler:(void (^)(dispatch_source_t timer))handler {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), (uint64_t)(interval *NSEC_PER_SEC), 0);
    // 设置回调
    dispatch_source_set_event_handler(timer, ^{
        if (mainThread) {
            //在主线程执行代码块
            dispatch_async(dispatch_get_main_queue(), ^{
                if (handler) {
                    handler(timer);
                }
            });
        } else {
            //在异步线程执行代码块
            if (handler) {
                handler(timer);
            }
        }
    });
    // 启动定时器
    if (startNow) {
        dispatch_resume(timer);
    }
    return timer;
}


+ (void) startTimer:(dispatch_source_t)timer {
    if (!timer) {
        return;
    }
    dispatch_resume(timer);
}

+ (void) stopTimer:(dispatch_source_t)timer {
    if (!timer) {
        return;
    }
    dispatch_source_cancel(timer);
}

@end
